package com.pet_service.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pet_service.entity.Permission;
import com.pet_service.entity.Role;
import com.pet_service.entity.UserRole;
import com.pet_service.result.Result;
import com.pet_service.service.PermissionService;
import com.pet_service.service.RoleService;
import com.pet_service.service.UserRoleService;
import com.pet_service.vo.GrantPermissionBean;
import com.pet_service.vo.PageBean;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 邹全伸
 * @version 1.0
 * @date 2025-09-23 10:34
 */
@Slf4j
@Tag(name = "角色模块")
@RestController//@Controller + @ResponseBody, 用于返回数据
@RequestMapping("/roles")
public class RoleController {
    @Resource
    private RoleService roleService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private PermissionService permissionService;

    //获取所有角色
    @GetMapping("/all")
    @PreAuthorize("hasAuthority('system:role:view')")
    public Result allRoles(){
        List<Role> roleList = roleService.list();
        return Result.ok(roleList);
    }

    ///分页获取角色
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:role:view')")
    public Result roleList(@RequestBody PageBean pageBean) {
        Page<Role> page = new Page<>(pageBean.getPageNum(), pageBean.getPageSize());
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        //where role_name like '%query%'
        queryWrapper.like(pageBean.getQuery() != null, "role_name", pageBean.getQuery().trim());
        IPage<Role> iPage = roleService.page(page, queryWrapper);
        List<Role> roleList = iPage.getRecords();
        for (Role role : roleList) {
            List<Permission> permissionList=permissionService.getPermissionsByRoleId(role.getId());
            role.setPermissionList(permissionList);
        }
        iPage.setRecords(roleList);
        return Result.ok(iPage);
    }

    //保存或更新角色
    @PostMapping("/saveOrUpdateRole")
    @PreAuthorize("hasAuthority('system:role:create')" + "||" + "hasAuthority('system:role:edit')")
    public Result saveOrUpdateRole(@RequestBody Role role) {
        log.info("role={}", role.getId());
        //mybatis-plus 提供的saveOrUpdate方法
        boolean flag = roleService.saveOrUpdate(role);
        return flag?Result.ok("操作成功!"):Result.fail("操作失败!");
    }

    //编写角色名称是否存在
    @Operation(summary = "检查角色名称是否存在", description = "根据角色名称查询")
    @GetMapping("/checkRoleName/{role_name}")
    @PreAuthorize("hasAuthority('system:role:view')")
    public Result checkRoleName(@PathVariable("role_name") String role_name) {
        log.info("检查角色名称: {}", role_name);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name", role_name);
        long count = roleService.count(queryWrapper);
        return count > 0 ? Result.fail("此角色名称已经存在！") : Result.ok("此角色名称可以使用！");
    }

    //编写角色编码是否存在
    @Operation(summary = "检查角色编码是否存在", description = "根据角色编码查询")
    @GetMapping("/checkRoleCode/{role_code}")
    @PreAuthorize("hasAuthority('system:role:view')")
    public Result checkRoleCode(@PathVariable("role_code") String role_code) {
        log.info("检查角色编码: {}", role_code);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_code", role_code);
        long count = roleService.count(queryWrapper);
        return count > 0 ? Result.fail("此角色编码已经存在！") : Result.ok("此角色编码可以使用！");
    }

    //删除角色
    @DeleteMapping
    //这个权限一定要在权限表中查看是否有这个权限
    @PreAuthorize("hasAuthority('system:role:delete')")
    public Result deleteRole(@RequestBody List<Integer> ids) {
        log.info("需要逻辑删除角色id:{}",ids);
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id",ids);
        long count = userRoleService.count(queryWrapper);
        if(count>0) {
            return Result.fail("此角色有用户使用不允许删除！");
        }
        //这里不用逻辑删除，物理删除，需要自己写sql
        return roleService.removeByRoleIdList(ids);
    }

    //授予权限
    @PostMapping("/grantPermission")
    @PreAuthorize("hasAuthority('system:role:permission')")
    public Result  grantPermission(@RequestBody GrantPermissionBean grantPermissionBean){
        log.info("授予权限={}",grantPermissionBean);
        return roleService.grantPermissionToRole(grantPermissionBean);
    }
}
